// JavaScript Document
//Depends on Company.UI
//Depends on Company.Utils
//Depends on Prototype

Company.UI.StartGrid = function(gridObject) {
	Event.observe(window, 'load', function() {
		Event.observe(window, 'keypress', gridObject.docOnKeypress.bindAsEventListener(gridObject));
		Event.observe(window, 'keydown', gridObject.docOnKeydown.bindAsEventListener(gridObject));

		$A($(gridObject.Id).rows).each(function(r) {
			Event.observe(r, 'click', gridObject.selectRowByEvent.bindAsEventListener(gridObject));
		});

		$$('#' + gridObject.Id + ' input.EditButton').each(function(b) {
			Event.observe(b, 'click', gridObject.editThisRowHandler.bindAsEventListener(gridObject))
		});

		$$('#' + gridObject.Id + ' input.CancelButton').each(function(b) {
			Event.observe(b, 'click', gridObject.cancelEditRowByEvent.bindAsEventListener(gridObject))
		});

		$$('#' + gridObject.Id + ' input.AddButton').each(function(b) {
			Event.observe(b, 'click', gridObject.insertRow.bindAsEventListener(gridObject))
		});

		Ajax.Responders.register(gridObject);

	});
}

/**
 *	@class This class containes all the javascript for a grid.
 *	@property {String} gridId
 *	@property {String} selectedClass
 *	@property {String} webServiceUrl
 */
Company.UI.Grid = Class.create();

Company.UI.Grid.prototype = {
	initialize: function(gridId, selectedClass, webServiceUrl) {
		this.Id = gridId;               //The id of the grid.
		this.selectedRowId = ''; 			//The id of the row that selected.
		this.selectedRowClass = ''; 		//The class that was used in this row before selected it.
		this.editionModeRow = ''; 		  //This is the row that we are editing right now.
		this.editionModeOn = false; 		//Are we editing or no?
		this.action = '';
		this.selectedCssClass = selectedClass;
		this.webServiceEndPoint = webServiceUrl;
	},
	docOnKeydown: function(evt) {
		var e = evt ? evt : window.event;
		if (!e) return;
		var key = 0;
		if (e.keyCode) {
			key = e.keyCode;
		} // for moz/fb, if keyCode==0 use 'which' 
		else if (typeof (e.which) != 'undefined') {
			key = e.which;
		}

		//alert(key);
		switch (key) {
			case 40:
				this.move(1);
				break
			case 38:
				this.move(-1);
				break;
			case 33:
				this.move(-10);
				break;
			case 34:
				this.move(10);
				break;
			case 36:
				this.moveFirst();
				break;
			case 35:
				this.moveLast();
				break;
			case 27:
				this.cancelEditRowById();
				break;
			case 45:
				if (e.shiftKey) {
					var ctr = $('btnAdd');
					if (ctr != null) {
						ctr.click();
					}
				}
				break;
			case 46:
				if (e.shiftKey) {
					var ctr = $('btnDelete');
					if (ctr != null) {
						ctr.click();
					}
				}
				break;
			default:
				break;
		}
	}, //ends docOnKeydown
	docOnKeypress: function(evt) {
		var e = evt ? evt : window.event;
		if (!e) return;
		var key = 0;
		if (e.keyCode) {
			key = e.keyCode;
		} // for moz/fb, if keyCode==0 use 'which' 
		else if (typeof (e.which) != 'undefined') {
			key = e.which;
		}

		//alert(key);
		switch (key) {
			case 13:
				this.editThisRowHandler(evt);
				break;
			case 112:
			case 80:
				if (e.shiftKey) {
					var ctr = $('btnPrint');
					if (ctr != null) {
						ctr.click();
					}
				}
				break;
			case 27:
				this.cancelEditRowById();
				break;
			default:
				break;
		}
	}, //end docOnKeypress 

	/**
	* Move the selectiong the number of places indicated
	*/
	move: function(places) {
		if (this.selectedRowId) {
			this.selectRowById(this.getRowId(places));
		}
	},
	/**
	*  Get the index relative to the selected row Id
	*/
	getRowId: function(index) {
		var pos = this.selectedRowId.lastIndexOf('_');
		var sI = this.selectedRowId.substring(pos + 1);
		var s = this.selectedRowId.substring(0, pos + 1);
		var newRowId = s + (eval(sI) + index);
		if ($(newRowId)) {
			return newRowId;
		} else {
			return this.selectedRowId;
		}
	},
	/**
	*  This method selects the first row in the grid
	*/
	moveFirst: function() {
		var grid = $(gridId);
		if (grid != null) {
			var row = grid.rows[1];
			this.selectRow(row);
		}
	},

	/**
	*  This method selected the last row in the grid
	*/
	moveLast: function() {
		var grid = $(gridId);
		if (grid != null) {
			var row = grid.rows[grid.rows.length - 1];
			this.selectRow(row);
		}
	},

	selectRowByEvent: function(event) {
		this.selectRow(Event.findElement(event, 'tr'));
	},
	/**
	*  This method unselect the previously selected row and select the new clicked one
	*/
	selectRowById: function(rowId) {
		if (rowId != this.selectedRowId) {
			this.selectRow($(rowId));
		}
	},

	selectRow: function(row) {
		if (row != null) {

			this.unSelectRow();
			this.selectedRowId = row.id;
			this.selectedRowClass = row.className;
			if (this.selectedCssClass == null || this.selectedCssClass + '' == 'undefined') {
				this.selectedCssClass = 'CellHighlighted';
			}
			row.className = this.selectedCssClass;
		}
	},

	/**
	*  This method unselect the given row id
	*/
	unSelectRow: function() {
		var row = $(this.selectedRowId);
		if (row != null) {
			row.className = this.selectedRowClass;
		}
	},

	editThisRowHandler: function(event) {
		if (this.editionModeOn) {
			this.saveThisRow();
		} else {
			this.selectRowByEvent(event);
			this.startEditRow();
		}
	},

	startEditRow: function() {
		var row = $(this.selectedRowId);
		var editTmp = $(this.Id + '_row_editable');
		var frmElement = null;

		if (row != null) {
			this.editionModeOn = true;
			this.editionModeRow = new Array(row.cells.length);

			var btnEdit = $(row.cells[0]).firstDescendant();
			btnEdit.value = "Save";

			var btnCancel = $(row.cells[row.cells.length - 1]).firstDescendant();
			btnCancel.disabled = false;

			for (c = 1; c < row.cells.length - 1; c++) {
				var cell = row.cells[c];
				this.editionModeRow[c] = cell.innerHTML;
				cell.innerHTML = editTmp.cells[c].innerHTML;

				frmElement = $(cell).firstDescendant();

				if (frmElement != null) {
					this.setFormElementValue(frmElement, this.editionModeRow[c]);
				}
			}
		}
	},

	//This method cancel the edit action
	cancelEditRowByEvent: function(event) {
		var row = Event.findElement(event, 'tr');
		this.cancelEditRow(row);
	},

	cancelEditRowById: function() {
		var row = $(this.selectedRowId);
		this.cancelEditRow(row);
	},

	cancelEditRow: function(row) {
		if (row != null) {

			var btnEdit = $(row.cells[0]).firstDescendant();
			btnEdit.value = "Edit";

			var btnCancel = $(row.cells[row.cells.length - 1]).firstDescendant();
			btnCancel.disabled = true;
			this.editionModeOn = false;
			for (c = 1; c < row.cells.length - 1; c++) {
				var cell = row.cells[c];
				cell.innerHTML = this.editionModeRow[c];
			}
		}
	},

	onComplete: function(result) {

		var row = $(this.selectedRowId);

		if (this.action == "edit") {
			if (row != null) {
				var btnEdit = $(row.cells[0]).firstDescendant();
				btnEdit.value = "Edit";

				var btnCancel = $(row.cells[row.cells.length - 1]).firstDescendant();
				btnCancel.disabled = true;
				this.editionModeOn = false;
				this.action = '';

				for (c = 1; c < row.cells.length - 1; c++) {
					var formElement = $(row.cells[c]).firstDescendant();
					row.cells[c].innerHTML = formElement.value;
				}
			}
		}
		if (this.action == "add") {

			this.editionModeOn = false;
			this.action = '';
			var oTable = $(this.Id);

			var oRow = oTable.insertRow(oTable.rows.length - 1);

			if (oTable.rows.length > 4) {
				this.addRow(oTable, row, oRow);
			} else {
				this.addFirstRow(oTable, row, oRow);
			}
		}
	},


	addFirstRow: function(oTable, row, oRow) {

		var templateRow = oTable.rows[oTable.rows.length - 1];
		oRow.className = "ClickCellLight";

		Event.observe(oRow, 'click', this.selectRowByEvent.bindAsEventListener(this));

		var d = new Date();
		oRow.id = this.Id + '_row_added_' + d.getHours() + '_' + d.getMinutes() + '_' + d.getSeconds() + '_' + d.getMilliseconds();

		var oCell = oRow.insertCell(0);

		oCell.innerHTML = "<input value=Edit onclick='' id=btnEdit name=btnEdit class=EditButton type=button>";

		Event.observe($(oCell).firstDescendant(), 'click', this.editThisRowHandler.bindAsEventListener(this));

		for (c = 1; c < row.cells.length - 1; c++) {
			oCell = oRow.insertCell(c);
			var formElement = $(row.cells[c]).firstDescendant();

			if (formElement != null) {
				oCell.innerHTML = formElement.value;
			}
		}

		oCell = oRow.insertCell(oRow.cells.length);
		oCell.innerHTML = "<input value=Cancel onclick='' id=btnCancel0 name=btnCancel0 class=CancelButton type=button>";
		Event.observe($(oCell).firstDescendant(), 'click', this.cancelEditRowByEvent.bindAsEventListener(this));
	},

	addRow: function(oTable, row, oRow) {

		var templateRow = oTable.rows[oTable.rows.length - 4];
		oRow.className = templateRow.className;

		Event.observe(oRow, 'click', this.selectRowByEvent.bindAsEventListener(this));

		var d = new Date();
		oRow.id = this.Id + '_row_added_' + d.getHours() + '_' + d.getMinutes() + '_' + d.getSeconds() + '_' + d.getMilliseconds();

		var oCell = oRow.insertCell(0);
		oCell.innerHTML = templateRow.cells[0].innerHTML;
		Event.observe($(oCell).firstDescendant(), 'click', this.editThisRowHandler.bindAsEventListener(this));

		for (c = 1; c < row.cells.length - 1; c++) {
			oCell = oRow.insertCell(c);
			var formElement = $(row.cells[c]).firstDescendant();

			if (formElement != null) {
				oCell.innerHTML = formElement.value;
			}
		}

		oCell = oRow.insertCell(oRow.cells.length);
		oCell.innerHTML = templateRow.cells[row.cells.length - 1].innerHTML;
		Event.observe($(oCell).firstDescendant(), 'click', this.cancelEditRowByEvent.bindAsEventListener(this));
	},



	onFailure: function(result) {
		alert("There was an Error when tring to save the values.");
	},


	insertOrUpdate: function() {
		var where = KeyField + "|E|" + this.getKeyValue() + "|";
		var fields = this.getFieldsToUpdate();
		var values = this.getValuesToUpdate();

		if (this.webServiceEndPoint.indexOf("?") != -1) {
			var urlArray = this.webServiceEndPoint.split("?");
			var url = urlArray[0] + '/Save?' + urlArray[1] + '&fields=' + fields + '&values=' + values + '&where=' + where;
		} else {
			var url = this.webServiceEndPoint + '/Save?fields=' + fields + '&values=' + values + '&where=' + where;
		}

		new Ajax.Request(url, {
			method: 'get',
			asynchronous: false,
			onFailure: this.displayError
		});
	},


	saveThisRow: function() {
		this.action = 'edit';
		this.insertOrUpdate();
	},

	insertRow: function(event) {
		this.selectRowByEvent(event);
		this.action = 'add';
		this.insertOrUpdate();
	},


	//Delete the record in the database in the selected row
	deleteRow: function() {
		var where = KeyField + "|E|" + this.getKeyValue() + "|";
		var result = DoCall(this.webServiceEndPoint + '/Delete?', where, "xml");
		var msg = result.selectSingleNode("/result").text;
		if (msg.toUpperCase() == 'OK') {
			$(selectedRowId).hide();
		} else {
			alert(msg);
		}
	},


	//This method sets the values for the form element in the editable row
	setFormElementValue: function(ctr, value) {
		switch (ctr.tagName.toUpperCase()) {
			case 'INPUT':
				switch (ctr.type.toUpperCase()) {
					case 'CHECKBOX':
						if (ctr.value.toUpperCase() != value.toUpperCase()) {
							ctr.checked = true;
						}
						break;
					case 'BUTTON':
						break;
					default:
						ctr.value = value;
						break;
				}
				break;
			case 'SELECT':
				for (i = 0; i < ctr.options.length; i++) {
					if (ctr.options[i].value.toUpperCase() == value.toUpperCase()) {
						ctr.options[i].selected = true;
					}
				}
				break;
		}
	},

	//Get the value of the key for this row
	getKeyValue: function() {
		var pos = this.selectedRowId.lastIndexOf('_');
		return KeyValues[this.selectedRowId.substring(pos + 1)];
	},

	//Build The QS with the fields in the row
	getFieldsToUpdate: function() {
		var frmElement = null;
		var f = '';

		var row = $(this.selectedRowId);

		for (c = 0; c < row.cells.length; c++) {
			frmElement = $("editColumn_" + c);
			pipe = '|';

			if (frmElement != null) {
				if (frmElement.type.toUpperCase() == 'BUTTON') {
					frmElement.name = "";
					pipe = "";
				}
				f += frmElement.name + pipe;
			}
		}
		return f;
	},

	//Build The QS with the values in the row
	getValuesToUpdate: function() {
		var frmElement = null;
		var v = '';
		var row = $(this.selectedRowId);


		for (c = 0; c < row.cells.length; c++) {
			frmElement = $("editColumn_" + c);
			pipe = '|';

			if (frmElement != null) {
				if (frmElement.type.toUpperCase() == 'CHECKBOX') {
					if (frmElement.checked == true) {
						frmElement.value = true;
					}
					else {
						frmElement.value = false;
					}
				}

				if (frmElement.type.toUpperCase() == 'BUTTON') {
					frmElement.value = "";
					pipe = "";
				}
				v += escape(frmElement.value) + pipe;
			}
		}
		return v;
	}
}
